class MyPageHeader extends BaseList {
    constructor(orderby, flag, $pagesize, $pagination, listUrl, onLineEditUrl, checkBoxName) {
        super(orderby, flag, $pagesize, $pagination, listUrl, onLineEditUrl, checkBoxName);
        this.pagenavbar = $("#wrapper__navbar");
        this.limit = 5;
        this.selectedItemList = {};  // 选定的数据列表OnMultiChoice
    }
    GetFilter(pageIndex) {
        let item = super.GetFilter(pageIndex);
        item['CurrentUserId'] = parseInt(parent.$("#UserId").val());         // 当前操作者，用于过滤供应商分组
        item['PoNoFilterValue'] = formatNullInputValue($.trim($("#PoNoFilterValue").val()));
        item['SupplierNameFilterValue'] = $("#SupplierNameFilterValue").val();
        item['StyleNoFilterValue'] = formatNullInputValue($.trim($("#StyleNoFilterValue").val()));
        item['PurchasedByNameFilterValue'] = formatNullInputValue($.trim($("#PurchasedByNameFilterValue").val()));
        item['IsSearchWnd'] = 1;      // 指示当前为检索画面
        //item['PayedFalg'] = 0;        // 没对账的才能被显示
        //item['CheckedStatus'] = 2;    // 只能是最终审核过的

        return JSON.stringify(item);
    }
    Search() {
        // 重新设置选择结果及清空明细
        this.ReSetLines();
        this.selectedItemList = {};
        $("#checkall-header").prop("checked", false);
        this.FetchForPage(1);
    }
    FetchAll() {
        $("#PoNoFilterValue").val("");
        $("#StyleNoFilterValue").val("");
        $("#PurchasedByNameFilterValue").val("");
        this.pagination.attr("_msh_page", 1);
        this.FetchForPage(1);
        // 重新设置选择结果及清空明细
        this.ReSetLines();
        this.selectedItemList = {};
        $("#checkall-header").prop("checked", false);
    }
    EmptyTableContent() {
        $("#tabData11 tbody").empty();
        this.pagination.attr("_msh_page", 1);
    }
    SetTableContent(result) {
        $("#tabData11 tbody").empty();
        let content_01 = '';
        this.rows = result.length;  // 设置表格中checkbox的数量为表格的行数
        this.numCheckbox = result.length;  // 设置表格中checkbox的数量为表格的行数
        for (let i = 0; i < result.length; i++) {
            content_01 = '<tr _mash_id="' + result[i].headerId + '">';
            content_01 += '<td style="padding-left:5px;"><label class="btn" for="R-' + result[i].headerId + '"><input id="R-' + result[i].headerId + '" name="_check_row_header" type="checkbox" onclick="_InstancePageHeader.DoCheckRow($(this),$(\'#checkall-header\'));" value="' + result[i].headerId + '"/><i></i><span></span></label></td>';
            content_01 += '<td>' + formatNullData(result[i].poNo) + '</td>';               // 订单号
            content_01 += '<td>' + formatNullData(result[i].styleNo) + '</td>';            // 订单款号
            content_01 += '<td>' + result[i].billTypeName + '</td>';                       // 合同类型
            content_01 += '<td>' + formatNullData(result[i].signedDate) + '</td>';         // 
            content_01 += '<td>' + formatNullData(result[i].orderArrivalDate) + '</td>';   //
            content_01 += '<td>' + formatNullData(result[i].supplierName) + '</td>';       // 供应商名称
            content_01 += '<td>' + formatNullData(result[i].purchasedByName) + '</td>';    // 采购担当
            content_01 += '<td style="border-right:none; text-overflow:ellipsis;" title="' + formatNullData(result[i].description) + '">' + formatNullData(result[i].description) + '</td>';        // 备注
            content_01 += '</tr>';

            $("#tabData11 tbody").append(content_01);
            content_01 = '';
        }
        setOneTableRowColor("tabData11");
        this.ResetSelectRowStatus();  // 恢复选定结果
    }
    DoCheckAll($self) {
        let _name = "input[type='checkbox'][name='" + this.checkBoxName + "']";
        let _this = this;
        if ($self.is(":checked") === true) {
            $(_name).each(function () {
                $(this).prop('checked', true);
                _this.SetRowStatus($(this), 1);
            });
        } else {
            $(_name).each(function () {
                $(this).prop("checked", false);
                _this.SetRowStatus($(this), 1);
            });
        }
        // 根据选择的订单，同步刷新明细列表
        if (Object.keys(this.selectedItemList).length > 0) {
            // 根据选择的订单，同步刷新明细列表
            _InstancePageLines.FetchForPage(1);
        } else {
            $('#tabData21 tbody').empty();
        }
        _InstancePageLines.selectedItemList = {};
        $("#wrapper__navbar_02").data("swPagination").options.max_page = 1;
        $("#wrapper__navbar_02").data("swPagination").options.current_page = 1; //当前页数
        $("#wrapper__navbar_02").data("swPagination").setPage(1);
        $("#checkall-lines").prop("checked", false);
    }
    DoCheckRow($self, $checkall) {
        let _name = "input[type='checkbox'][name='" + this.checkBoxName + "']:checked";
        let _checkedRows = $(_name).length;
        if (_checkedRows < this.numCheckbox) {
            $checkall.prop("checked", false);
        } else {
            $checkall.prop("checked", true);
        }
        this.SetRowStatus($self, 0);
    }
    // 设置行选择后的状态
    SetRowStatus($self, flag) {
        super.AdjustRowStatus($self, ($row, index) => {
            let key = $self.val();
            let item = {};
            // 为翻页选择做准备
            item["PoHeaderId"] = key;
            item["PoNo"] = $.trim($row.find('td').eq(1).text());
            this.selectedItemList[key] = item;
        }, ($row, index) => {
            let key = $self.val();
            delete this.selectedItemList[key];
        });
        if (flag === 0) {
            if (Object.keys(this.selectedItemList).length > 0) {
                // 根据选择的订单，同步刷新明细列表
                _InstancePageLines.FetchForPage(1);
            } else {
                $('#tabData21 tbody').empty();
                $("#wrapper__navbar_02").data("swPagination").options.max_page = 1;
                $("#wrapper__navbar_02").data("swPagination").options.current_page = 1; //当前页数
                $("#wrapper__navbar_02").data("swPagination").setPage(1);
            }
            // 同时也清空明细选择结果
            _InstancePageLines.selectedItemList = {};
            $("#checkall-lines").prop("checked", false);
        }
    }
    // 每次翻页都恢复选定结果
    ResetSelectRowStatus() {
        let _this = this;
        $("#tabData11 tbody").find("tr").each(function (index) {
            let key = $(this).attr("_mash_id");
            if (_this.selectedItemList[key] !== undefined) {
                $(this).children("td").eq(0).children("label").eq(0).children("input[type='checkbox'][name='_check_row_header']").eq(0).prop('checked', true);
                $(this).addClass("row__selected");
            }
        });
        // 设置选择全部的状态
        let n = $("input[type='checkbox'][name='_check_row_header']:checked").length;
        if (n < $("#tabData11 tbody").find("tr").length || n === 0) {
            $("#checkall-header").prop("checked", false);
        } else {
            $("#checkall-header").prop("checked", true);
        }
    }
    // 重新设置明细选择结果（清空）
    ReSetLines() {
        $('#tabData21 tbody').empty();
        $("#wrapper__navbar_02").data("swPagination").options.max_page = 1;
        $("#wrapper__navbar_02").data("swPagination").options.current_page = 1; //当前页数
        $("#wrapper__navbar_02").data("swPagination").setPage(1);
        $("#checkall-lines").prop("checked", false);
        _InstancePageLines.selectedItemList = {};
    }
    // 选择后执行的动作
    SetChoiceData($self) {
        // 设置选择结果
        let $row = $self.parent().parent().parent();
        // 返回选择结果 0:id 1:name 2:no
        return new Array($self.val(), $row.find('td').eq(2).text(), $row.find('td').eq(1).text());
    }
    SortTable(orderBy) {
        this.orderby = orderBy;
        // 得到排序数据
        this.FetchForPage(1);
    }
}

class MyPageLines extends BaseList {
    constructor(orderby, flag, $pagesize, $pagination, listUrl, onLineEditUrl, checkBoxName) {
        super(orderby, flag, $pagesize, $pagination, listUrl, onLineEditUrl, checkBoxName);
        this.pagenavbar = $("#wrapper__navbar_02");
        this.limit = 10;
        this.selectedItemList = {};
        this.loading__indicator = $("#loading__indicator_02");
        this.loading__indicator_i = $("#loading__indicator_02 i");
    }
    GetFilter(pageIndex) {
        let item = super.GetFilter(pageIndex);
        item['StockInHeaderId'] = parseInt(parent.$("#HeaderId").val());
        item['MaterialNameFilterVal'] = formatNullInputValue($.trim($("#MaterialNameFilterValue_03").val()));
        item['SpecificationFilterVal'] = formatNullInputValue($.trim($("#SpecificationFilterValue_03").val()));
        item['StyleNoFilterVal'] = formatNullInputValue($.trim($("#StyleNoFilterValue_03").val()));
        item['MaterialColourNameFilterVal'] = formatNullInputValue($.trim($("#MaterialColourNameFilterValue_03").val()));
        item['MaterialCodeFilterVal'] = formatNullInputValue($.trim($("#MaterialNoFilterValue_03").val()));
        // 得到选择的订单
        if (Object.keys(_InstancePageHeader.selectedItemList).length > 0) {
            let _headerIdList = [];
            for (let key in _InstancePageHeader.selectedItemList) {
                _headerIdList.push(parseInt(key));
            }
            item['HeaderIdList'] = _headerIdList;
        } else {
            item['HeaderIdList'] = null;
        }

        return JSON.stringify(item);
    }
    FetchAll() {
        $("#MaterialNameFilterValue_03").val("");
        $("#MaterialNoFilterValue_03").val("");
        $("#StyleNoFilterValue_03").val("");
        $("#SpecificationFilterValue_03").val("");
        $("#MaterialColourNameFilterValue_03").val("");
        this.pagination.attr("_msh_page", 1);
        this.FetchForPage(1);
    }
    EmptyTableContent() {
        $("#tabData21 tbody").empty();
        this.pagination.attr("_msh_page", 1);
    }
    SetTableContent(result) {
        $("#tabData21 tbody").empty();
        let content_01 = '';
        this.rows = result.length;         // 设置表格中checkbox的数量为表格的行数
        this.numCheckbox = result.length;  // 设置表格中checkbox的数量为表格的行数
        for (let i = 0; i < result.length; i++) {
            content_01 = '<tr _mash_id="' + result[i].linesId + '">';
            content_01 += '<td><label style="margin-left:3px;" class="btn" for="R-' + result[i].linesId + '"><input id="R-' + result[i].linesId + '" name="_check_row_lines" type="checkbox" onclick="_InstancePageLines.DoCheckRow($(this),$(\'#checkall-lines\'));" value="' + result[i].linesId + '"/><i></i><span></span></label></td>';
            content_01 += '<td>' + formatNullData(result[i].poNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].styleNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].materialCode) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].materialName) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].materialColourName) + '</td>';                   // 色名
            content_01 += '<td>' + formatNullData(result[i].specification) + '</td>';                        // 规格
            content_01 += '<td style="text-align:center;">' + formatNullData(result[i].uomName) + '</td>';   // 单位
            content_01 += '<td style="border-right:none;">' + result[i].poQuantity + '</td>';                // 订单数量
            content_01 += '</tr>';

            $("#tabData21 tbody").append(content_01);
            content_01 = '';
        }
        setOneTableRowColor("tabData21");
        this.ResetSelectRowStatus();  // 恢复选定结果
    }
    SetSelectLinesStatus() {
        if ($("#checkall-lines").is(":checked") === false)
            $("#checkall-lines").click();
    }
    // 设置行选择后的状态
    SetRowStatus($self) {
        super.AdjustRowStatus($self, ($row, index) => {
            let key = $self.val();
            let item = {};
            // 为翻页选择做准备
            item["PoLinesId"] = key;
            this.selectedItemList[key] = item;
        }, ($row, index) => {
            let key = $self.val();
            delete this.selectedItemList[key];
        });
    }
    // 每次翻页都恢复选定结果
    ResetSelectRowStatus() {
        let _this = this;
        $("#tabData21 tbody").find("tr").each(function (index) {
            let key = $(this).attr("_mash_id");
            if (_this.selectedItemList[key] !== undefined) {
                $(this).children("td").eq(0).children("label").eq(0).children("input[type='checkbox'][name='_check_row_lines']").eq(0).prop('checked', true);
                $(this).addClass("row__selected");
            }
        });
        // 设置选择全部的状态
        let n = $("input[type='checkbox'][name='_check_row_lines']:checked").length;
        if (n < $("#tabData21 tbody").find("tr").length || n === 0) {
            $("#checkall-lines").prop("checked", false);
        } else {
            $("#checkall-lines").prop("checked", true);
        }
        
        if ($("#SelectAll").is(":checked") === true) {
            if ($("#checkall-lines").is(":checked") === false)
                $("#checkall-lines").click();
        }
    }
}

// 最后结果
function OnMultiChoice() {
    // 判断是否做了选择
    if (Object.keys(_InstancePageHeader.selectedItemList).length > 0 && Object.keys(_InstancePageLines.selectedItemList).length > 0) {
        let result = [];
        result.push(_InstancePageHeader.selectedItemList);
        result.push(_InstancePageLines.selectedItemList);
        result["SelectAllFlag"] = $("#SelectAll").is(":checked") ? 1 : 0;       // 全选标记
        result['MaterialNameFilterValue'] = formatNullInputValue($.trim($("#MaterialNameFilterValue_03").val()));
        result['SpecificationFilterValue'] = formatNullInputValue($.trim($("#SpecificationFilterValue_03").val()));
        result['StyleNoFilterValue'] = formatNullInputValue($.trim($("#StyleNoFilterValue_03").val()));
        result['MaterialColourNameFilterValue'] = formatNullInputValue($.trim($("#MaterialColourNameFilterValue_03").val()));
        result['MaterialNoFilterValue'] = formatNullInputValue($.trim($("#MaterialNoFilterValue_03").val()));

        parent.arrChoice.push(result);
        parent.choice_success = true;

        closePopupWnd();
    } else {
        parent.choice_success = false;
        ShowErrorMessagePanel("请选择采购订单及明细。");
    }
}

let _InstancePageHeader = null;
let _InstancePageLines = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    // 从url得到相关参数
    wndflag = jQuery.url.param("wndflag") === undefined ? null : jQuery.url.param("wndflag"); // 指示用来引用的模块标识(51 表示入库单)    
    // 设置供应商过滤
    $("#SupplierNameFilterValue").val(parent.$("#SupplierName").val());

    _InstancePageHeader = new MyPageHeader(null, 1, null, $("#page_indicator_block"),
            "/purchase/po/header/fetchForPage.html", null, "_check_row_header");
    _InstancePageLines = new MyPageLines(null, 1, null, $("#page_indicator_block_02"),
            "/purchase/po/lines/fetchForPageByPoNo.html", null, "_check_row_lines");

    // 设置分页控制 （操作区域）
    $("#wrapper__navbar").swPagination({
        link_string: '/?page={page_number}',
        max_page: null,
        paged: function (page) {
            $("#page_indicator_block").attr("_msh_page", page);
            _InstancePageHeader.FetchForPage(page);
        }
    });

    $("#wrapper__navbar_02").swPagination({
        link_string: '/?page={page_number}',
        max_page: null,
        paged: function (page) {
            $("#page_indicator_block_02").attr("_msh_page", page);
            _InstancePageLines.FetchForPage(page);
        }
    });
    $("#loading__indicator_02").hide();
    SetSearchWnd();

    _InstancePageHeader.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
}

function SetSearchWnd() {
    $("div.search").unbind('keyup');
    
    let clazz = 'search--active';
    // 设置引入订单表头的搜索
    let $search_02 = $('#search_02');
    // 搜索按钮
    $('#search_btn_02').on('click', function (event) {
        $search_02.addClass(clazz);
        $search_02.on(window.transitionProp, function (event) {
            $search_02.find('input').first().focus();
        });
    });
    // 搜索窗口关闭
    $('#search__form_butclose_02').on('click', function (event) {
        $search_02.removeClass(clazz);
    });
    // 搜索框回车直接进行搜索
    $("#search_02").bind('keyup', function (e) {
        let key = e.keyCode;
        if (key === 13) {
            $("#but_filter_02").click();
        }
    });
    
    // 设置引入订单明细的搜索
    let $search_03 = $('#search_03');
    // 搜索按钮
    $('#search_btn_03').on('click', function (event) {
        $search_03.addClass(clazz);
        $search_03.on(window.transitionProp, function (event) {
            $search_03.find('input').first().focus();
        });
    });
    // 搜索窗口关闭
    $('#search__form_butclose_03').on('click', function (event) {
        $search_03.removeClass(clazz);
    });
    // 搜索框回车直接进行搜索
    $("#search_03").bind('keyup', function (e) {
        let key = e.keyCode;
        if (key === 13) {
            $("#but_filter_03").click();
        }
    });
}